package com.chuangmei.com.myscreenrecorderdemo;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int RECORD_REQUEST_CODE = 101;
    private static final int STORAGE_REQUEST_CODE = 102;
    private static final int AUDIO_REQUEST_CODE = 103;

    private Button mBT_bind;
    private MediaProjection mediaProjection;//录制视频的工具
    private MediaProjectionManager projectionManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        if (initData()) {
            projectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
            // 启动 RecordService
            startService(new Intent(this, RecordService.class));

            mBT_bind = this.findViewById(R.id.mBT_bind);
            mBT_bind.setOnClickListener(this);

            initPermission();
            Intent intent = new Intent(this, RecordService.class);
            bindService(intent, connection, BIND_AUTO_CREATE);
        }
    }

    private boolean initData() {
        boolean flag = true;
        //判定系统版本过低
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {

        } else {
            Toast.makeText(this, "Android版本太低，无法使用该功能", Toast.LENGTH_SHORT).show();
            mBT_bind.setEnabled(false);
            mBT_bind.setVisibility(View.GONE);
            flag = false;
        }
        return flag;
    }

    /**
     * 初始化权限
     */
    private void initPermission() {
        List<String> list = new ArrayList<>();
        int i = 0;
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager
                .PERMISSION_GRANTED) {
            list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            i++;
            //            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
            // .WRITE_EXTERNAL_STORAGE}, 102);
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager
                .PERMISSION_GRANTED) {
            list.add(Manifest.permission.RECORD_AUDIO);
            i++;
            //            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 103);
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager
                .PERMISSION_GRANTED) {
            list.add(Manifest.permission.CAMERA);
            i++;
            //            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 104);
        }
        if (i > 0) {
            String[] strings = list.toArray(new String[i]);
            ActivityCompat.requestPermissions(this, strings, RECORD_REQUEST_CODE);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 102) {
            Toast.makeText(this, "缺少读写权限", Toast.LENGTH_SHORT).show();
            return;
        }
        if (requestCode == 103) {
            Toast.makeText(this, "缺少录音权限", Toast.LENGTH_SHORT).show();
            return;
        }
        if (requestCode == 104) {
            Toast.makeText(this, "缺少相机权限", Toast.LENGTH_SHORT).show();
            return;
        }
        if (requestCode != 101) {
            Log.e("HandDrawActivity", "error requestCode =" + requestCode);
        }
        if (resultCode != RESULT_OK) {
            Toast.makeText(this, "捕捉屏幕被禁止", Toast.LENGTH_SHORT).show();
            return;
        }
        mediaProjection = projectionManager.getMediaProjection(resultCode, data);
        recordService.setMediaProject(mediaProjection);
        /*获得服务状态回调*/
        recordService.recordingEndListener(new ServiceCallBack() {
            @Override
            public void onStart() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "屏幕开始录制...", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onStop(final String filePath) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "视频保存成功，地址：" + filePath, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        //开始录屏
        if (recordService.startRecord()) {
            mBT_bind.setText("停止录屏");
        } else {//开启失败
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "屏幕录制开启失败", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /**
     * 如果不授予权限则关闭应用
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == RECORD_REQUEST_CODE) {
            for (int results : grantResults) {
                if (results != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "缺少录屏所需权限", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }

        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mBT_bind:
                if (recordService.isRunning()) {
                    recordService.stopRecord();
                    mBT_bind.setText("开始录屏");
                } else {
                    Intent captureIntent = projectionManager.createScreenCaptureIntent();
                    startActivityForResult(captureIntent, RECORD_REQUEST_CODE);//正常情况是要执行到这里的,作用是申请捕捉屏幕
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        /*解绑服务*/
        if (recordService.isRunning()) {
            recordService.stopRecord();
            unbindService(connection);
        }
        super.onDestroy();
    }

    private RecordService recordService;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
        /*绑定服务后回调*/
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            RecordService.RecordBinder binder = (RecordService.RecordBinder) service;
            recordService = binder.getRecordService();
            //设置屏幕宽高和dpi
            recordService.setScreenSize(metrics.widthPixels, metrics.heightPixels, metrics.densityDpi);
            mBT_bind.setEnabled(true);
            mBT_bind.setText(recordService.isRunning() ? "停止录屏" : "开始录屏");
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
        }
    };
}
